package com.orangelife.mobile.surrounding.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.common.sp.ShoppingSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.activities.biz.InnerListView;
import com.orangelife.mobile.common.activity.PullRefreshBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.surrounding.adapter.HotGoodsListViewAdapter;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.surrounding.biz.SurroundHttpBiz;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.ta.utdid2.android.utils.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 周边商品搜索
 * <p/>
 * Created by yyx.Modify by wgf on 160408
 * on 2015/10/10.
 *
 * @author yyx
 */
public class SearchConditionActivity extends PullRefreshBaseActivity {

    @Bind(R.id.iv_search)
    ImageView ivSearch;
    @Bind(R.id.et_search_goods)
    EditText etSearchGoods;
    @Bind(R.id.lvSearch)
    InnerListView lvAutoComplete;
    @Bind(R.id.tvClearHistory)
    TextView tvClearHistory;
    @Bind(R.id.btnSearch)
    Button btnSearch;

    @Bind(R.id.view)
    View view;
    @Bind(R.id.pullListView)
    PullToRefreshListView pullListView;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    /** 搜索结果 */
    private List<Map<String, Object>> data = new ArrayList<>();
    private HotGoodsListViewAdapter<Map<String, Object>> adapter;

    /** 关键字列表数据 */
    private ArrayList<String> listKeyword = new ArrayList<>();

    /** 历史记录列表数据 */
    private ArrayList<String> listHistory = new ArrayList<>();
    private final int INTELL_CODE = 2;
    private final int KEYWORD_CODE = 1;
    private final int WHAT_SEARCH_REFRESH = 3;

    /** 关键字结果列表适配器 */
    private ArrayAdapter<String> AutoCompleteAdapter;

    /** 历史记录列表适配器 */
    private ArrayAdapter<String> historyAdapter;


    /** 关键词 */
    private String mStrKeyword = "";

    private static final String HISTORY_LIST = "GoodsHistoryList";
    /** 是否是自动补全的关键词 */
    private boolean isKeyWord = false;
    private boolean isFirstReq = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circumtesco_selectcondition);
        ButterKnife.bind(this);
        initView();
        initHistoryList();
        setAdapter();
        setXListViewAndEmptyLayoutListener(pullListView, emptyLayout, adapter);
        setListener();
        pullListView.setVisibility(View.GONE);
        dismissProgress();
    }

    @Override
    protected void requestWhenPullRefresh() {
        if (isFirstReq) {
            isFirstReq = false;
        } else {
            mStrKeyword = etSearchGoods.getText().toString();
            requestResultListByKeyword(KEYWORD_CODE);
        }
    }

    private void initView() {
        lvAutoComplete.setVisibility(View.VISIBLE);
    }

    private void setAdapter() {
        adapter = new HotGoodsListViewAdapter<>(this, data);
    }

    private void setListener() {
        tvClearHistory.setOnClickListener(listener);
        btnSearch.setOnClickListener(listener);
        ivSearch.setOnClickListener(listener);
        lvAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                /*请求该关键字的结果，然后将结果赋值给结果列表，然后notify；*/
                mStrKeyword = isKeyWord ? listKeyword.get(position) : listHistory.get(position);
                etSearchGoods.setText(mStrKeyword);
                etSearchGoods.setSelection(mStrKeyword.length());
                requestResultListByKeyword();
                saveLocalSearchHistory(mStrKeyword);
                /*记录搜索**/
                hideInputMethod(view);
            }
        });

        etSearchGoods.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = s.toString();
                if (input.equals("")) {/*关键词为空*/
                    hideResultList();
                    historyAdapter = new ArrayAdapter<>(SearchConditionActivity.this,
                            android.R.layout.simple_list_item_1, listHistory);
                    lvAutoComplete.setAdapter(historyAdapter);
                    isKeyWord = false;
                } else {
                    /* 取最后一个字符，如果输入的是空字符串，则不处理 */
                    String inputLastChar = input.substring(input.length() - 1);
                    if (inputLastChar.equals(" ") || inputLastChar.equals("")) {/*输入为空则不处理*/
                        return;
                    }
                    requestKeywordAutoComplete(input);
                }
            }
        });

        etSearchGoods.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    mStrKeyword = etSearchGoods.getText().toString();
                    requestResultListByKeyword();
                    saveLocalSearchHistory(mStrKeyword);
                    hideInputMethod(v);
                }
                return false;
            }
        });
    }

    private void requestKeywordAutoComplete(String input) {
        Map<String, Object> map = new HashMap<>();
        map.put("comID", CommSp2.getCommID());
        try {
            map.put("keyword", URLEncoder.encode(input, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("type", 6);
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_CIRCUMTESO_KEYWORD_FILLED, map, handler, INTELL_CODE, HttpUtil.ACTION_URI);
    }

    private void requestResultListByKeyword() {
        closeDialog();
        currentReqMode = REQ_MODE_INIT;
        showProgress();
        requestResultListByKeyword(KEYWORD_CODE);
    }


    /** 根据关键字搜索结果 */
    private void requestResultListByKeyword(int what) {
        Map<String, Object> map = new HashMap<>();
        map.put("comID", CommSp2.getCommID());
        try {
            map.put("keyword", URLEncoder.encode(mStrKeyword, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("type", 6);
        map.put("pageIndex", pageNo);
        map.put("pageSize", pageSize);
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_CIRCUMTESO_KEYWORD_RESULT, map, handler, what, HttpUtil.ACTION_URI);
    }


    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tvClearHistory:
                    listHistory.clear();
                    historyAdapter = new ArrayAdapter<>(SearchConditionActivity.this,
                            android.R.layout.simple_list_item_1, listHistory);
                    lvAutoComplete.setAdapter(historyAdapter);
                    isKeyWord = false;
                    break;
                case R.id.btnSearch:
                    //跳转到搜索结果界面，显示搜索结果
                    break;
                case R.id.iv_search:
                    mStrKeyword = etSearchGoods.getText().toString();
                    if (StringUtils.isEmpty(mStrKeyword)) {
                        ToastHelper.getInstance()._toast("请输入要搜索的内容");
                        return;
                    }
                    requestResultListByKeyword();
                    saveLocalSearchHistory(mStrKeyword);
                    break;
                default:
                    break;
            }
        }
    };

    @SuppressWarnings("unchecked")
    private void handleKeyWordAutoComplete(String result) {
        hideResultList();
        listKeyword.clear();
        Map<String, Object> map = JSONHelper.jsonToMap(result);
        if (map != null && map.get("pageEntity") != null && !"".equals(map.get("pageEntity"))) {
            ArrayList<HashMap<String, String>> keywordAutoCompleteList = (ArrayList<HashMap<String, String>>) map.get("pageEntity");
            if (keywordAutoCompleteList != null) {
                int size = keywordAutoCompleteList.size() > 10 ? 10 : keywordAutoCompleteList.size();
                for (int i = 0; i < size; i++) {
                    listKeyword.add(keywordAutoCompleteList.get(i).get("keyword"));
                }
            }
        }
        AutoCompleteAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, listKeyword);
        lvAutoComplete.setAdapter(AutoCompleteAdapter);
        isKeyWord = true;
    }

    private void hideResultList() {
        pullListView.setVisibility(View.GONE);
        lvAutoComplete.setVisibility(View.VISIBLE);
        tvClearHistory.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
    }

    private void showResultList() {
        pullListView.setVisibility(View.VISIBLE);
        lvAutoComplete.setVisibility(View.GONE);
        tvClearHistory.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case KEYWORD_CODE:
                    showResultList();
                    List list2 = JsonReponseHandler.getListFromJson(String.valueOf(msg.obj), adapter, null);
                    handleAfterRequest(isConnected(false), SurroundHttpBiz.getGoodListTotal(msg.obj), list2, pullListView, adapter);
                    isKeyWord = true;
                    break;
                case INTELL_CODE:
                    handleKeyWordAutoComplete(msg.obj.toString());
                    break;
                case 500:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    isLogin(null);
                    break;
                default:
                    break;
            }
        }

    };


    /**
     * 获取本地的历史记录
     *
     * @return
     */
    public void initHistoryList() {
        listHistory.clear();
        String searchHistoryList = ShoppingSp.getGoodSearchHistory();
        if (!searchHistoryList.equals("0")) {
            String[] tmp = searchHistoryList.split("##");

            for (int i = 0; i < tmp.length; i++) {
                if (!StringUtil.isBlank(tmp[i])) {
                    listHistory.add(tmp[i]);
                }
            }
            // int size = new Random().nextInt(6);
//            for (int i = 0; i < historyList.size(); i++) {
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("keyword", historyList.get(i));
//                historySearchList.add(map);
//            }
        }
//        historySearchAdapter.notifyDataSetChanged();
        if (listHistory.size() != 0) {
            tvClearHistory.setVisibility(View.VISIBLE);
            view.setVisibility(View.VISIBLE);
            isKeyWord = false;
        }
    }

    /**
     * 添加历史记录
     *
     * @param keyword
     */
    private void saveLocalSearchHistory(String keyword) {
        for (int i = 0; i < listHistory.size(); i++) {
            if (listHistory.get(i).equals(keyword)) {
                return;
            }
        }
        listHistory.add(keyword);
    }

    /**
     * 保存历史记录到本地
     */
    private void saveHistoryToLocalFile() {
        int i = 0;
        int size = listHistory.size();
        StringBuilder sb = new StringBuilder();

        while (size > 0) {

            String s = listHistory.get(size - 1);
            listHistory.remove(size - 1);
            if (("#" + sb).indexOf("#" + s + "#") < 0 && !"".equals(s)) {
                sb.append(s);
                sb.append("##");
            }
            size = listHistory.size();
        }
        ShoppingSp.setGoodSearchHistory(sb.toString());
    }

    @Override
    protected EmptyLayout getEmptyLayout() {
        return emptyLayout;
    }

    @Override
    protected List getData() {
        return data;
    }

    @Override
    protected int getDataCount() {
        return data == null ? 0 : data.size();
    }

    /***
     * 关闭软键盘
     *
     * @param v
     */
    private void hideInputMethod(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    @Override
    public void onBackClick(View v) {
        saveHistoryToLocalFile();
        this.finish();
    }
}
